// ==UserScript==
// @name         Adblock Experimental
// @namespace    https://gitee.com/hziee514/
// @version      0.1
// @description  try to take over the world!
// @author       46084337@qq.com
// @match        *://*/*
// @icon         
// @grant        none
// @run-at       document-start
// @require      https://gitee.com/hziee514/tampermonkey-script/raw/master/rules.js?13
// ==/UserScript==

(function() {
    'use strict';

    function blockNode(node) {
        if (node.tagName == 'SCRIPT' || node.tagName == 'IFRAME') {
            if (window.isBlockUrl(node.src)) {
                console.log("blockNode:", node.tagName, node.src);
                node.remove();
            } else {
                console.debug('newNode:', node.tagName, node.src);
            }
        } else if (node.classList && node.classList.contains('adsbygoogle')) {
            console.log("blockAd:", node.tagName, node);
            //node.remove();
            node.style.display = 'none';
        }
    }
    const observer = new MutationObserver(function(mutations){
        mutations.forEach(function(mutation){
            mutation.addedNodes.forEach(blockNode);
        });
    });
    observer.observe(document.head, {childList:true});
    window.addEventListener('DOMContentLoaded', function() {
        observer.observe(document.body, { childList: true, subtree: true });
    });

    document.querySelectorAll('script[src]').forEach(script => {
        console.debug('found script:', script.src);
        if (window.isBlockUrl(script.src)) {
            console.log('blockScript:', script.src);
            script.remove();
        }
    });

    document.querySelectorAll(".adsbygoogle").forEach(function(node){
        console.log('removeAd:', node.tagName, node);
        //node.remove();
        node.style.display = 'none';
    });

    const originalFetch = window.fetch;
    window.fetch = function(url, options) {
        if (window.isBlockUrl(url)) {
            console.log('blockFetch:', url);
            return Promise.reject(new Error('请求被拦截'));
        }
        return originalFetch(url, options);
    };

    const originalOpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function(method, url) {
        if (window.isBlockUrl(url)) {
            console.log('block XHR::open:', url);
            return; // 阻止请求
        }
        originalOpen.apply(this, arguments);
    };
})();